# Copyright (c) 2017 Presto Labs Pte. Ltd.
# Author: inkyu

import os
import ujson as json
import json as base_json
import functools

from coin.base.book.types import TradeSide, create_market_trade_event
from coin.exchange.base.ws.handler import WebsocketHandler
from coin.exchange.huobi.ws.subscriber import parse_channel
from coin.exchange.huobi.book_builder import BookBuilder
from coin.exchange.huobi.kr_rest.product import HuobiProduct


@functools.lru_cache(maxsize=128)
def get_product_from_channel_name(channel):
  symbol, _ = parse_channel(channel)
  return HuobiProduct.FromStrNativeProduct(symbol)


class HuobiHandler(WebsocketHandler):
  def on_ws_book(self, record, queue_data, topic_data):
    data = record.data
    if not isinstance(data, dict) and not isinstance(data, list):
      data = json.loads(data.tobytes())

    product = get_product_from_channel_name(data['ch'])
    native_symbol = product.native_symbol
    if not self.is_subscribed('book', native_symbol):
      return

    book = self._books.get(native_symbol, None)
    if book is not None and book._seq_num_successive:
      # Since diff update is successive, let's not interrupt.
      return

    book = BookBuilder(native_symbol, book_builder_observer=self._book_builder_observer)
    bids = data['tick']['bids']
    asks = data['tick']['asks']

    book.snapshot(bids, asks)
    book.update_timestamp(record.timestamp)
    book.update_topic_id(record.topic_id)
    self._books[native_symbol] = book
    self.ready = True
    if self._feed_checker:
      self._feed_checker.on_book(product=product, book=book, timestamp=record.timestamp)
    self.publish_event('book', book.symbol, book)

  def on_ws_diff(self, record, queue_data, topic_data):
    data = record.data
    if not isinstance(data, dict) and not isinstance(data, list):
      data = json.loads(data.tobytes())

    product = get_product_from_channel_name(data['ch'])
    native_symbol = product.native_symbol
    if not self.is_subscribed('book', native_symbol):
      return

    book = self._books.get(native_symbol, None)
    if book is None:
      return

    bids = data['tick']['bids']
    asks = data['tick']['asks']
    seq_num = data['tick']['seqNum']
    prev_seq_num = data['tick']['prevSeqNum']

    book.update_diff(bids, asks, seq_num, prev_seq_num)
    book.update_timestamp(record.timestamp)
    book.update_topic_id(record.topic_id)
    if self._feed_checker:
      self._feed_checker.on_book(product=product, book=book, timestamp=record.timestamp)
    self.publish_event('book', book.symbol, book)

  def on_ws_trade(self, record, queue_data, topic_data):
    data = record.data
    if not isinstance(data, dict) and not isinstance(data, list):
      try:
        data = json.loads(data.tobytes())
      except ValueError:
        data = base_json.loads(data.tobytes())

    product = get_product_from_channel_name(data['ch'])
    native_symbol = product.native_symbol
    if not self.is_subscribed('trade', native_symbol):
      return

    data = data['tick']
    for data in data['data']:
      price = float(data['price'])
      qty = float(data['amount'])
      if data['direction'] == 'buy':
        side = TradeSide.TRADE_BUY_SIDE
      elif data['direction'] == 'sell':
        side = TradeSide.TRADE_SELL_SIDE
      else:
        raise ValueError('Unknown side: %s', data)
      trade_event = create_market_trade_event(record.timestamp,
                                              native_symbol,
                                              price,
                                              qty,
                                              side,
                                              topic_id=record.topic_id)
      if self._feed_checker:
        self._feed_checker.on_trade(product=product,
                                    trade_event=trade_event,
                                    timestamp=record.timestamp)
      self.publish_event('trade', native_symbol, trade_event)

  # Deprecated
  on_ws_depth = on_ws_book


if ('RUST_FEED_HANDLER' in os.environ) and os.environ['RUST_FEED_HANDLER'] == '1':
  try:
    from native_rust import feed_handler

    class HuobiRustHandler(HuobiHandler):
      def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._rust_handler = feed_handler.HuobiHandler()
        self._rust_handler.register_book_callback(functools.partial(self.publish_event, 'book'))

      def post_subscribe(self, event_type, symbol, callback):
        assert type(symbol) == str
        if event_type == 'book':
          self._rust_handler.register_book_symbol(symbol)

      def on_ws_book(self, record, queue_data, topic_data):
        if isinstance(record.data, (dict, list)):
          record_bytes = json.dumps(record.data).encode()
        else:
          record_bytes = record.data.tobytes()
        self._rust_handler.on_snapshot(record.timestamp, record_bytes, {}, {})

      def on_ws_diff(self, record, queue_data, topic_data):
        pass

      on_ws_depth = on_ws_book

    HuobiHandler = HuobiRustHandler
  except ImportError:
    import logging
    logging.warning('Unable to import rust feed_handler.')
